package com.tulingxueyuan.mall.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tulingxueyuan.mall.common.api.CommonResult;
import com.tulingxueyuan.mall.common.exception.ApiException;
import com.tulingxueyuan.mall.dto.*;
import com.tulingxueyuan.mall.modules.oms.model.OmsOrder;
import com.tulingxueyuan.mall.modules.oms.service.OmsOrderService;

import com.tulingxueyuan.mall.modules.oms.service.TradeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.PublicKey;
import java.util.*;


@RestController
@Api(tags = "OrderController",description = "订单服务接口")
@RequestMapping("/order")
@Slf4j
@ResponseBody
public class OrderController {


    @Autowired
   private OmsOrderService orderService;
    @Autowired
    private TradeService tradeService;


    /**
     *  加入购物车---生成确认订单实现
     *  立即购买—生成确认订单实现 product_id  sku_id. 改成DTO接收
     *    复用业务逻辑的代码 product_id 和sku_id 查出购物车对象所需要信息
     *  初始化确认订单的商品和收货地址信息
     * this.axios.post('/order/generateConfirmOrder',Qs.stringify({itemIds: constStore.itemids}
     */
    @PostMapping(value="/generateConfirmOrder")
    public CommonResult generateConfirmOrder(generateConfirmOrderDTO generateConfirmOrderDTO){

        ConfirmOrderDTO confirmOrderDTO= orderService.generateConfirmOrder(generateConfirmOrderDTO);
         return CommonResult.success(confirmOrderDTO) ;
    }
    /**
     *  生成订单(下单）
     * this.axios
     *           .post("/order/generateOrder", {
     */
    @PostMapping(value="/generateOrder")

    public CommonResult generateOrder(@RequestBody OrderParamDTO paramDTO){
        OmsOrder omsOrder = orderService.generateOrder(paramDTO);
        return CommonResult.success(omsOrder.getId());
    }
    /**  读取下单成功后的订单详情
     *   this.axios.get(`/order/orderDetail?orderId=${this.orderId}`).then((res)=>{
     */
    @GetMapping("/orderDetail")
    public CommonResult getOrderDetail(@RequestParam("orderId") Long id){
        OrderDetailDTO dto=  orderService.getOrderDetail(id);
        return CommonResult.success(dto);

    }
    /**
     * 我的订单列表
     * this.axios.post('/order/list/userOrder'
     */
    @PostMapping("/list/userOrder")
    public CommonResult getMyOrders(@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                    @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
        IPage<OrderListDTO> myOrders = orderService.getMyOrders(pageSize, pageNum);

        return CommonResult.success(myOrders);

    }

    /**
     * /order/tradeQrCode
     * 生成支付宝当面付二维码
     *
     */
    @PostMapping("/tradeQrCode")
    public CommonResult tradeQrCode(@RequestParam("orderId") Long orderId,
                                    @RequestParam("payType") Integer payType) throws IllegalAccessException {
        if (payType>2||payType<0){
            throw new ApiException("支付类型参数错误!");
        }
        return tradeService.tradeQrCode(orderId,payType);

    }

    @PostMapping("/paySuccess/{payType}")
    public void getpaySuccess(@PathVariable("payType") Integer payType,
                              HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {

        /**
         * 更新订单状态和支付方式       唯一标识 id
         * 清除锁定库存 扣除实际库存
         * 删除二维码
         */
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {

            String name = (String) iter.next();
            if (!name.toLowerCase().equals("sign_type"));
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsRlHUO8M5gad/4TAmautiIS1uLxravBg8KXqZJw3VcHRQfBwx9jCcK1gRo4wPku5h1JXYaYD9RXbJYVfaMH6AW/VXOuwcoQaFf77tuNI3aBJHK7xdl2dhV4BbKAi9jOOcun1Dka2Eds8TvpjBoBLW9qyKkZTSqIJVwd4MFT1hUIDlG8DDzd8Tu/5oQFiE/EQ2aPzTQXeU/VXsNVSy8k0pOGcTTq0mkFAwW431Yyk+k7+mNmiLd/ipcgshhLNfOGpUJ289DOjlMi85QfnMMfqzloHnbKjDHhcAYoIvqfw3MeUy+bI0SkS4Y1MH6T2Zm3v4wWx66EffXaiVFV/AdmkwQIDAQAB";

        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, "UTF-8", "RSA2"); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //订单id
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            if (StrUtil.isNotBlank(out_trade_no) && NumberUtil.isNumber(out_trade_no)){
               Long orderId=Long.parseLong(out_trade_no);
                orderService.paySuccess(orderId,payType);
                log.info("支付成功");

            }
        }else {
            System.out.println("验签失败");
        }
    }








}
